﻿using AutoMapper;
using ORS.OrderRobot.Domain;
using ORS.OrderRobot.Domain.Entity;
using ORS.OrderRobot.IOC;
using ORS.OrderRobot.ServiceContracts;
using ORS.OrderRobot.ServiceContracts.Dtos;
using ORS.OrderRobot.ServiceContracts.ThirdPartApi;

namespace ORS.OrderRobot.Service
{
	public class FlightInfoService : IFlightInfoService, IScoped
    {
        private readonly IRepository<FlightInfo, int> _airlinesRepository;
        private readonly IMapper _mapper;
        private readonly IThirdSystemService _thirdSystemService;
        /// <summary>
        /// 中国的航空公司
        /// </summary>
        private Dictionary<string, string> ChinaAirlines = new Dictionary<string, string>{
            {"3U", "四川航空"},
            {"8L", "云南祥鹏航空"},
            {"AQ", "九元航空"},
            {"BK", "奥凯航空"},
            {"CA", "中国国际航空"},
            {"CZ", "中国南方航空公司"},
            {"DR", "苏南瑞丽航空"},
            {"G5", "华夏航空有限公司"},
            {"GJ", "长龙航空"},
            {"GS", "天津航空"},
            {"HO", "上海吉祥航空"},
            {"HU", "海南航空"},
            {"JD", "北京首都航空"},
            {"KN", "中国联合航空"},
            {"MF", "厦门航空"},
            {"MU", "中国东方航空公司"},
            {"NS", "河北航空"},
            {"PN", "中国西部航空"},
            {"QW", "青岛航空"},
            {"SC", "山东航空"},
            {"ZH", "深圳航空"},
            {"NX", "澳门航空"}
        };
        public FlightInfoService(
            IRepository<FlightInfo, int> airlinesRepository,
            IMapper mapper,
            IThirdSystemService thirdSystemService
        )
		{
            _airlinesRepository = airlinesRepository;
            _mapper = mapper;
            _thirdSystemService = thirdSystemService;
		}


        public async Task CreateOrUpdateAsync(FlightInfoDto input)
        {
            var entity = await GetEntity(input.AirlineCode,input.FlightNo);
            if (entity != null)
            {
                entity.PickupStoreCode = input.PickupStoreCode;
                await _airlinesRepository.UpdateAsync(entity);
            }
            else
            {
                entity = _mapper.Map<FlightInfo>(input);
                await _airlinesRepository.InsertAsync(entity);
            }
        }

        public async Task<List<FlightInfoDto>> GetList(GetAirlineInput input)
        {
            var entitys = await _airlinesRepository.GetListAsync(x => x.AirlineCode == input.AirLineCode);
            if (!string.IsNullOrEmpty(input.FlightNo))
            {
                entitys = entitys.Where(i => i.FlightNo == input.FlightNo).ToList();
            }
            return _mapper.Map<List<FlightInfoDto>>(entitys);
        }
        /// <summary>
        /// 从远程同步数据
        /// </summary>
        /// <returns></returns>
        public async Task<int> SyncFromRemote()
        {
            DateTime currentDateTime = DateTime.Now.China();
            string datePart = currentDateTime.ToString("yyyy/MM/dd");
            string timePart = currentDateTime.ToString("HH:mm");
            var data = await _thirdSystemService.FetchFlightInfo(datePart, timePart);
            var chinaAirlineKeys = ChinaAirlines.Keys;
            var chinaData = data.Where(d => chinaAirlineKeys.Contains(d.AirlineCode, StringComparer.OrdinalIgnoreCase)).ToList();

            // 先查出所有已存在的航班（一次查出，减少数据库IO）
            var airlineCodes = chinaData.Select(d => d.AirlineCode).Distinct().ToList();
            var flightNos = chinaData.Select(d => d.FlightNo).Distinct().ToList();
            var existList = await _airlinesRepository.GetListAsync(x => airlineCodes.Contains(x.AirlineCode) && flightNos.Contains(x.FlightNo));
            var existDict = existList.ToDictionary(x => x.AirlineCode + "_" + x.FlightNo);

            var toUpdate = new List<FlightInfo>();
            var toInsert = new List<FlightInfo>();
            foreach (var cData in chinaData)
            {
                var key = cData.AirlineCode + "_" + cData.FlightNo;
                if (existDict.TryGetValue(key, out var existEntity))
                {
                    existEntity.PickupStoreCode = cData.PickupStoreCode;
                    toUpdate.Add(existEntity);
                }
                else
                {
                    var entity = _mapper.Map<FlightInfo>(cData);
                    toInsert.Add(entity);
                }
            }
            if (toUpdate.Count > 0)
                await _airlinesRepository.UpdateManyAsync(toUpdate);
            if (toInsert.Count > 0)
                await _airlinesRepository.InsertManyAsync(toInsert);
            return chinaData.Count;
        }

        public async Task<FlightInfoDto?> GetFlightInfo(string airlineCode, string flightNo)
        {
            var entity = await GetEntity(airlineCode, flightNo);
            if (entity == null) return null;
            return _mapper.Map<FlightInfoDto>(entity);
        }

        private async Task<FlightInfo?> GetEntity(string airlineCode, string flightNo)
        {
            //找到航空公司
            var entitys = await _airlinesRepository.GetListAsync(x => x.AirlineCode == airlineCode);
            if (entitys != null && entitys.Any())
            {
                //找到该条航班的
                var entity = entitys.FirstOrDefault(x => x.FlightNo == flightNo);
                if(entity == null)
                {
                    var backupEntity =  entitys.First();
                    backupEntity.PickupStoreCode = "00030";
                    return backupEntity;
                }
                return entity;
            }
            return null;
        }
    }
}

